package nc.plugin;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.ucf.mdf.util.HttpClientUtil;
import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.logging.Logger;
import nc.bs.pub.pa.PreAlertObject;
import nc.bs.pub.taskcenter.BgWorkingContext;
import nc.bs.pub.taskcenter.IBackgroundWorkPlugin;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.jdbc.framework.processor.MapProcessor;
import nc.pubitf.para.SysInitQuery;
import nc.vo.am.common.util.CollectionUtils;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDate;

import java.util.*;

public class VoucherUploadAttachPlugin implements IBackgroundWorkPlugin {

    private BaseDAO baseDAO;

    public BaseDAO getBaseDAO() {
        return baseDAO == null ? new BaseDAO() : baseDAO;
    }

    @Override
    public PreAlertObject executeTask(BgWorkingContext bgWorkingContext) throws BusinessException {
        YFKHandlerUtil util = new YFKHandlerUtil();

        // 获取入参，时间范围，减少查询数据
        LinkedHashMap<String, Object> keyMap = bgWorkingContext.getKeyMap();
        String beginTime = (String)keyMap.get("beginTime");
        String endTime = (String)keyMap.get("endTime");
        if(beginTime == null){
            // 获取近三天数据
            beginTime = DateUtil.offsetDay(DateUtil.date(), -3).toString("yyyy-MM-dd") + " 00:00:00";
        }
        if(endTime == null){
            endTime = DateUtil.format(new Date(), "yyyy-MM-dd") + " 23:59:59";
        }

        // 1、获取当前发票是否与友费控有关联
        List<Map<String, Object>> vocherList =  getGLAndYFKBillRelevance(beginTime, endTime);
        if(CollectionUtils.isEmpty(vocherList)) return null;

        // 遍历YFKATTACH_XLOG附件记录
        for(Map<String,Object> map : vocherList) {
            try{
                String pk_voucher = (String) map.get("pk_voucher");
                String creator = (String) map.get("creator"); // 凭证创建人

                // 2、上传发票到NC65单据中
                List<JSONObject> attachs = util.getYFKAttachsByNCKey(pk_voucher, map);
                if(attachs == null || attachs.isEmpty()) return null;
                util.getBIPAttachService().uploadAttachToBIPInputStream(pk_voucher, "", creator, attachs);
            }catch (Exception e){
                Logger.error("下载附件异常: " + e.getMessage());
                continue;
            }
        }
        return null;
    }

    /**
     * 构建NC65与友费控关联的SQL,过滤掉已上传的附件
     * @return
     * @throws BusinessException
     */
    private List<Map<String, Object>> getGLAndYFKBillRelevance(String beginTime, String endTime) throws BusinessException{
        StringBuilder sql = new StringBuilder();
        sql.append(" select distinct ");
        sql.append("    glv.creator creator, glv.pk_voucher pk_voucher, fr.src_freedef1 lycode,fr.src_billtype lybilltype,fr.src_system lysystem,  ");
        sql.append("    fr.des_billtype mdbilltype,fr.des_freedef1,fr.des_system mdsystem,fr.des_busidate mdbusidate");
        sql.append("  from gl_voucher glv ");
        sql.append(" inner join fip_relation fr on glv.pk_voucher = fr.des_relationid ");
        sql.append("  left join YFKATTACH_XLOG yx on glv.pk_voucher = yx.pk_glid ");
        sql.append(" where 1 = 1 and glv.dr = 0 and fr.dr = 0  ");
        sql.append("   and  yx.pk_glid IS NULL");
//        sql.append("   and glv.PK_VOUCHER = '1001A110000000LP4LZY'  ");
        sql.append("   and fr.des_billtype = 'C0' and fr.src_system in ('EM','FIP') ");// FIP代表费控
        sql.append(" and creationtime between '"+beginTime+" 00:00:00'  AND '"+endTime+" 23:59:59' ");
        List<Map<String, Object>> sqlResult =  (List<Map<String, Object>>) this.getBaseDAO().executeQuery(sql.toString(), new MapListProcessor());
        if (CollectionUtils.isEmpty(sqlResult)) {
            return null;
        }
        return sqlResult;
    }

}
